import torch
import torch.nn as nn
import torch.nn.functional as F


class BasicBlock1D(nn.Module):
    """1D基本残差块，对应ResNet18/34"""
    expansion = 1

    def __init__(self, in_channels, out_channels, stride=1, downsample=None):
        super(BasicBlock1D, self).__init__()

        self.conv1 = nn.Conv1d(in_channels, out_channels, kernel_size=7, stride=stride,
                               padding=3, bias=False)
        self.bn1 = nn.BatchNorm1d(out_channels)

        self.conv2 = nn.Conv1d(out_channels, out_channels, kernel_size=7, stride=1,
                               padding=3, bias=False)
        self.bn2 = nn.BatchNorm1d(out_channels)

        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        identity = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            identity = self.downsample(x)

        out += identity
        out = self.relu(out)

        return out


class ResNet1D(nn.Module):
    """1D ResNet主模型"""

    def __init__(self, block, layers, num_classes=4, input_channels=1):
        super(ResNet1D, self).__init__()

        self.in_channels = 64

        # 初始卷积层 - 适配1D数据
        self.conv1 = nn.Conv1d(input_channels, 64, kernel_size=15, stride=2,
                               padding=7, bias=False)
        self.bn1 = nn.BatchNorm1d(64)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool1d(kernel_size=3, stride=2, padding=1)

        # 四个残差层，对应ResNet34的[3,4,6,3]结构
        self.layer1 = self._make_layer(block, 64, layers[0])
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2)

        # 自适应平均池化 + 全连接层
        self.avgpool = nn.AdaptiveAvgPool1d(1)
        self.fc = nn.Linear(512 * block.expansion, num_classes)

        # 权重初始化
        for m in self.modules():
            if isinstance(m, nn.Conv1d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, nn.BatchNorm1d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def _make_layer(self, block, out_channels, blocks, stride=1):
        downsample = None

        # 当需要下采样或通道数变化时，使用1x1卷积调整捷径连接
        if stride != 1 or self.in_channels != out_channels * block.expansion:
            downsample = nn.Sequential(
                nn.Conv1d(self.in_channels, out_channels * block.expansion,
                          kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm1d(out_channels * block.expansion),
            )

        layers = []
        layers.append(block(self.in_channels, out_channels, stride, downsample))

        self.in_channels = out_channels * block.expansion

        for _ in range(1, blocks):
            layers.append(block(self.in_channels, out_channels))

        return nn.Sequential(*layers)

    def forward(self, x):
        # 输入x形状: (batch_size, 1, 268)

        x = self.conv1(x)  # -> (128, 64, 134)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)  # -> (128, 64, 67)

        x = self.layer1(x)  # -> (128, 64, 67)
        x = self.layer2(x)  # -> (128, 128, 34)
        x = self.layer3(x)  # -> (128, 256, 17)
        x = self.layer4(x)  # -> (128, 512, 9)

        x = self.avgpool(x)  # -> (128, 512, 1)
        x = torch.flatten(x, 1)  # -> (128, 512)
        x = self.fc(x)  # -> (128, 4)

        return x


def resnet34_1d(num_classes=4, input_channels=1):
    """创建1D ResNet34模型"""
    return ResNet1D(BasicBlock1D, [3, 4, 6, 3], num_classes, input_channels)
